package cn.edu.nju.software.zp13.core2.xmlNodeEntity;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DomPrinter {
	private final char treeBranchUnit = '\t';

	public void print(Node node) {
		print(node, 0);
	}

	public void print(Node node, int depth) {
		short nodeType = node.getNodeType();
		if (nodeType == Node.TEXT_NODE) {
			printlnTreeNode(depth, node.getNodeValue());
		} else {
			printlnTreeNode(depth, node.getNodeName());
		}
		NodeList nodes = node.getChildNodes();
		depth++;
		for (int i = 0; i < nodes.getLength(); i++) {
			Node n = nodes.item(i);
			print(n, depth);
		}
	}

	private void println(String s) {
		System.out.println(s);
	}

	private String treeBranch(int length) {
		char[] treeBranch = new char[length];
		for (int i = 0; i < treeBranch.length; i++) {
			treeBranch[i] = treeBranchUnit;
		}
		return new String(treeBranch);
	}

	private void printlnTreeNode(int depth, String content) {
		println(treeBranch(depth) + content);
	}

}
